package client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.util.Vector;


public class ConnectionData {
	public ServerKey key = new ServerKey();
	
	private static String filename = "src//ssl//clientData//serverKeys";
	
	@SuppressWarnings("unchecked")
	public static Vector<ServerKey> readKeys() {
		InputStream fis = null;
		try {
			File file = new File(filename);
			if(file.exists()) {
				fis = new FileInputStream(filename);
				ObjectInputStream o = new ObjectInputStream(fis);
				Vector<ServerKey> keys = (Vector<ServerKey>) o.readObject();
				if(keys == null) {
					System.out.println("Fehler beim lesen der serverKey Datei, erzeuge neue Datei");
					keys = new Vector<ServerKey>();
					writeKeys(keys);
				}
				return keys;
			} else {
				System.out.println("Neue serverKey Datei erzeugt");
				return new Vector<ServerKey>();
			}
			

		} catch (IOException e) {
			System.err.println(e);
		} catch (ClassNotFoundException e) {
			System.err.println(e);
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}
	
	public KeyPair getPubKey() {
		
			Vector<ServerKey> keys = readKeys();
			
			for(int i=0; i<keys.size();i++) {
				if(keys.get(i).host.equals(key.host)) {
					return keys.get(i).serverPublicKey;
				}
			}
			
			return null;
		
	}
	
	public static int inList(Vector<ServerKey> keys, String host) {
		for(int i=0; i<keys.size();i++) {
			if(keys.get(i).host.equals(host)) {
				return i;
			}
		}
		
		return -1;
	}
	
	public static void addKey(String host, KeyPair key) {
		Vector<ServerKey> keys = readKeys();
		System.out.println(keys + " " + host);
		if(inList(keys, host) == -1) {
			ServerKey connData = new ServerKey();
			connData.host = host;
			connData.serverPublicKey = key;
			keys.add(connData);
		}
		
		writeKeys(keys);
	}
	
	public static void writeKeys(Vector<ServerKey> keys) {
		OutputStream fos = null;

		try {
			fos = new FileOutputStream(filename);
			ObjectOutputStream o = new ObjectOutputStream(fos);
			o.writeObject(keys);
		} catch (Exception e) {
			System.err.println(e);
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

}
